package implementation;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import started.LerEntrada;
import entility.Job;
import entility.JobImpl;
import entility.Machine;
import entility.Notification;
import entility.Range;

public class ThreadExecute extends Thread{

	public Job job;
	public static OutrosHosts[] others;
	public static Range range;
	
	
	public ThreadExecute(Job job){
		this.job = job;
	}
	
	
	public void run() {
		
		List<Integer> ids  = new ArrayList<Integer>();
		int lines = 5000;
		
		
		this.setHostsAndRanges(job);


		try {
			
			LerEntrada l = new LerEntrada();
			int  value =  1;

			int count = 0;
			while (value != 0) {

				value = l.getNextNumber();
				

				if(range.contains(value))
				{
					count++;
					ids.add(value);
					if(count % lines == 0)
					{
						if(Notification.print)
							System.out.println("adiciona na Job List 50000 linhas");
						Job newJob = new JobImpl(Notification.HOST);
						newJob.setMethod("addToJobList");
						newJob.setDataInt(new ArrayList<Integer>(ids));
						HostImpl.jobController.add(newJob);
						ids.clear();
					}
				}
				else
				{
					insertInOtherHost(value);

				}

			}



		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	

	public void setHostsAndRanges(Job job)
	{
		Map<Machine, List<Range>> ranges = job.getRangeMap();
		if(ranges.size() > 1)
			others = new OutrosHosts[ranges.size()-1];
		else
			others = null;

		int count  = 0;
		for(Machine mac: ranges.keySet() )
		{
			if(mac.ip.equals(HostImpl.meMyselfandI.ip))
			{
				range = ranges.get(mac).get(0);
				
			}
			else
			{
				others[count] =  new OutrosHosts(mac, ranges.get(mac).get(0));
				count++;
			}

		}

		

	}
	
	private void insertInOtherHost(Integer value) {

		if(others != null)
		{
			for(OutrosHosts s:others)
			{
				try{
					if(s.canInsert(value))
					{
						s.Insert(value);
						break;
					}

				}catch(Exception e)
				{
					e.printStackTrace();
				}
			}

		}
	}

	
}
